import React, { useState, useEffect } from 'react';
import { issuerApi } from '../../services/apiService';

const IssuerPage = () => {
  // 状态管理
  const [issuerDid, setIssuerDid] = useState(null);
  const [schemas, setSchemas] = useState([]);
  const [credentials, setCredentials] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('identity');
  const [newSchema, setNewSchema] = useState({
    name: '',
    description: '',
    type: '',
    attributes: {}
  });
  const [newCredential, setNewCredential] = useState({
    schemaId: '',
    subjectDid: '',
    attributes: {},
    expirationDate: ''
  });
  const [attributeFields, setAttributeFields] = useState({
    key: '',
    value: ''
  });
  const [issuedCredentialPreview, setIssuedCredentialPreview] = useState(null);

  // 初始化加载
  useEffect(() => {
    fetchIssuerDid();
    fetchSchemas();
    fetchCredentials();
  }, []);

  // 获取发行方DID
  const fetchIssuerDid = async () => {
    setLoading(true);
    try {
      const response = await issuerApi.getCurrentIssuerDID();
      if (response.success) {
        setIssuerDid(response.issuerDID);
      }
      setError(null);
    } catch (err) {
      setError('获取发行方DID失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 创建发行方DID
  const createIssuerDid = async () => {
    setLoading(true);
    try {
      const response = await issuerApi.createIssuerIdentity();
      if (response.success) {
        setIssuerDid(response.issuerDID);
        setError(null);
      }
    } catch (err) {
      setError('创建发行方DID失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 发布发行方状态
  const publishState = async () => {
    setLoading(true);
    try {
      const response = await issuerApi.publishIssuerState();
      if (response.success) {
        alert(`发行方状态已发布到链上，交易哈希: ${response.transactionHash}`);
        setError(null);
      }
    } catch (err) {
      setError('发布发行方状态失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 获取Schema列表
  const fetchSchemas = async () => {
    setLoading(true);
    try {
      const response = await issuerApi.listSchemas();
      if (response.success) {
        setSchemas(response.schemas);
        setError(null);
      }
    } catch (err) {
      setError('获取Schema列表失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 创建Schema
  const createSchema = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await issuerApi.createSchema(newSchema);
      if (response.success) {
        setSchemas([...schemas, response.schema]);
        setNewSchema({
          name: '',
          description: '',
          type: '',
          attributes: {}
        });
        setError(null);
      }
    } catch (err) {
      setError('创建Schema失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 添加属性字段
  const addAttributeField = () => {
    if (attributeFields.key && attributeFields.key.trim() !== '') {
      setNewSchema({
        ...newSchema,
        attributes: {
          ...newSchema.attributes,
          [attributeFields.key]: {
            type: 'string',
            description: attributeFields.value || attributeFields.key
          }
        }
      });
      setAttributeFields({ key: '', value: '' });
    }
  };

  // 获取凭证列表
  const fetchCredentials = async () => {
    setLoading(true);
    try {
      const response = await issuerApi.listCredentials();
      if (response.success) {
        setCredentials(response.credentials);
        setError(null);
      }
    } catch (err) {
      setError('获取凭证列表失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 发行凭证
  const issueCredential = async (e) => {
    e.preventDefault();
    if (!newCredential.schemaId || !newCredential.subjectDid) {
      setError('Schema ID和接收方DID为必填项');
      return;
    }
    
    setLoading(true);
    try {
      const response = await issuerApi.issueCredential(newCredential);
      if (response.success) {
        // 存储凭证数据在组件状态中
        const issuedCredential = {
          id: response.credentialId,
          schemaId: newCredential.schemaId,
          subjectDid: newCredential.subjectDid,
          issuanceDate: new Date().toISOString(),
          expirationDate: newCredential.expirationDate,
          credential: response.credential // 新增: 保存完整凭证数据
        };
        
        setCredentials([...credentials, issuedCredential]);
        setNewCredential({
          schemaId: '',
          subjectDid: '',
          attributes: {},
          expirationDate: ''
        });
        setError(null);
        
        // 显示成功消息和凭证预览
        setIssuedCredentialPreview(response.credential);
      }
    } catch (err) {
      setError('发行凭证失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 撤销凭证
  const revokeCredential = async (id) => {
    if (!confirm('确定要撤销此凭证吗？此操作不可逆。')) {
      return;
    }
    
    setLoading(true);
    try {
      const response = await issuerApi.revokeCredential(id);
      if (response.success) {
        setCredentials(credentials.map(cred => 
          cred.id === id ? { ...cred, revoked: true } : cred
        ));
        alert('凭证已成功撤销');
        setError(null);
      }
    } catch (err) {
      setError('撤销凭证失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 更新凭证属性
  const updateCredentialAttribute = (key, value) => {
    setNewCredential({
      ...newCredential,
      attributes: {
        ...newCredential.attributes,
        [key]: value
      }
    });
  };

  // 复制凭证JSON到剪贴板
  const copyCredentialToClipboard = () => {
    if (issuedCredentialPreview) {
      navigator.clipboard.writeText(JSON.stringify(issuedCredentialPreview, null, 2))
        .then(() => {
          alert('凭证JSON已复制到剪贴板！现在您可以切换到"钱包">"导入凭证"粘贴此内容。');
        })
        .catch(err => {
          console.error('复制失败:', err);
          alert('复制失败，请手动选择并复制凭证JSON。');
        });
    }
  };

  // 关闭凭证预览
  const closeCredentialPreview = () => {
    setIssuedCredentialPreview(null);
  };

  return (
    <div className="container py-4">
      {/* 错误提示 */}
      {error && (
        <div className="alert alert-danger mb-4" role="alert">
          <i className="bi bi-exclamation-triangle-fill me-2"></i> {error}
        </div>
      )}
      
      {/* 凭证预览 */}
      {issuedCredentialPreview && (
        <div className="alert alert-success mb-4" role="alert">
          <div className="d-flex justify-content-between align-items-start">
            <div>
              <h5 className="alert-heading">
                <i className="bi bi-check-circle-fill me-2"></i>
                凭证发行成功！
              </h5>
              <p>凭证ID: {issuedCredentialPreview.id}</p>
              <p className="mb-0">
                接收方现在可以导入此凭证。请复制下方JSON并发送给接收方，或者自行导入到您的钱包。
              </p>
            </div>
            <button 
              type="button" 
              className="btn-close" 
              onClick={closeCredentialPreview}
              aria-label="Close"
            ></button>
          </div>
          
          <hr />
          
          <div className="mt-3">
            <div className="bg-light p-3 rounded mb-3" style={{ maxHeight: '200px', overflow: 'auto' }}>
              <pre className="mb-0" style={{ whiteSpace: 'pre-wrap' }}>
                {JSON.stringify(issuedCredentialPreview, null, 2)}
              </pre>
            </div>
            <div className="d-flex gap-2">
              <button 
                className="btn btn-primary" 
                onClick={copyCredentialToClipboard}
              >
                <i className="bi bi-clipboard me-2"></i>
                复制凭证JSON
              </button>
              <a 
                href={`/wallet/credentials/import?prefill=${encodeURIComponent(JSON.stringify(issuedCredentialPreview))}`}
                className="btn btn-outline-primary"
                target="_blank"
              >
                <i className="bi bi-box-arrow-up-right me-2"></i>
                打开导入页面
              </a>
            </div>
          </div>
        </div>
      )}
      
      {/* 标签栏 */}
      <ul className="nav nav-tabs mb-4">
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'identity' ? 'active' : ''}`}
            onClick={() => setActiveTab('identity')}>
            身份管理
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'schemas' ? 'active' : ''}`}
            onClick={() => setActiveTab('schemas')}>
            Schema管理
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'credentials' ? 'active' : ''}`}
            onClick={() => setActiveTab('credentials')}>
            凭证发行
          </button>
        </li>
      </ul>
      
      {/* 身份管理 */}
      {activeTab === 'identity' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title">发行方身份</h3>
            {issuerDid ? (
              <div>
                <p className="mb-2">当前DID：</p>
                <div className="alert alert-success">
                  <code>{issuerDid}</code>
                </div>
                <button 
                  className="btn btn-primary me-2"
                  onClick={publishState}
                  disabled={loading}>
                  {loading ? '处理中...' : '发布状态到链上'}
                </button>
              </div>
            ) : (
              <div>
                <p className="mb-3">您尚未创建发行方身份。</p>
                <button 
                  className="btn btn-primary"
                  onClick={createIssuerDid}
                  disabled={loading}>
                  {loading ? '处理中...' : '创建发行方DID'}
                </button>
              </div>
            )}
          </div>
        </div>
      )}
      
      {/* Schema管理 */}
      {activeTab === 'schemas' && (
        <div>
          <div className="card mb-4">
            <div className="card-body">
              <h3 className="card-title mb-3">创建Schema</h3>
              <form onSubmit={createSchema}>
                <div className="mb-3">
                  <label className="form-label">名称</label>
                  <input 
                    type="text"
                    className="form-control"
                    value={newSchema.name}
                    onChange={(e) => setNewSchema({...newSchema, name: e.target.value})}
                    required
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">描述</label>
                  <textarea 
                    className="form-control"
                    value={newSchema.description}
                    onChange={(e) => setNewSchema({...newSchema, description: e.target.value})}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">类型</label>
                  <input 
                    type="text"
                    className="form-control"
                    value={newSchema.type}
                    onChange={(e) => setNewSchema({...newSchema, type: e.target.value})}
                    required
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">属性</label>
                  <div className="input-group mb-2">
                    <input 
                      type="text"
                      className="form-control"
                      placeholder="属性名"
                      value={attributeFields.key}
                      onChange={(e) => setAttributeFields({...attributeFields, key: e.target.value})}
                    />
                    <input 
                      type="text"
                      className="form-control"
                      placeholder="描述（可选）"
                      value={attributeFields.value}
                      onChange={(e) => setAttributeFields({...attributeFields, value: e.target.value})}
                    />
                    <button 
                      type="button" 
                      className="btn btn-outline-secondary"
                      onClick={addAttributeField}>
                      添加
                    </button>
                  </div>
                  {Object.keys(newSchema.attributes).length > 0 && (
                    <div className="alert alert-light">
                      <h6>当前属性列表：</h6>
                      <ul className="mb-0">
                        {Object.keys(newSchema.attributes).map(key => (
                          <li key={key}>{key}: {newSchema.attributes[key].description}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
                <button 
                  type="submit" 
                  className="btn btn-primary"
                  disabled={loading}>
                  {loading ? '处理中...' : '创建Schema'}
                </button>
              </form>
            </div>
          </div>

          <div className="card">
            <div className="card-body">
              <h3 className="card-title mb-3">Schema列表</h3>
              {schemas.length === 0 ? (
                <p className="text-muted">暂无Schema记录</p>
              ) : (
                <div className="table-responsive">
                  <table className="table table-hover">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>创建时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      {schemas.map(schema => (
                        <tr key={schema.id}>
                          <td><small>{schema.id}</small></td>
                          <td>{schema.name}</td>
                          <td>{schema.type}</td>
                          <td>{new Date(schema.created).toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* 凭证发行 */}
      {activeTab === 'credentials' && (
        <div>
          <div className="card mb-4">
            <div className="card-body">
              <h3 className="card-title mb-3">发行新凭证</h3>
              <form onSubmit={issueCredential}>
                <div className="mb-3">
                  <label className="form-label">Schema</label>
                  <select 
                    className="form-select"
                    value={newCredential.schemaId}
                    onChange={(e) => setNewCredential({...newCredential, schemaId: e.target.value})}
                    required>
                    <option value="">选择Schema</option>
                    {schemas.map(schema => (
                      <option key={schema.id} value={schema.id}>
                        {schema.name} ({schema.type})
                      </option>
                    ))}
                  </select>
                </div>
                <div className="mb-3">
                  <label className="form-label">接收方DID</label>
                  <input 
                    type="text"
                    className="form-control"
                    value={newCredential.subjectDid}
                    onChange={(e) => setNewCredential({...newCredential, subjectDid: e.target.value})}
                    required
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">过期日期（可选）</label>
                  <input 
                    type="date"
                    className="form-control"
                    value={newCredential.expirationDate}
                    onChange={(e) => setNewCredential({...newCredential, expirationDate: e.target.value})}
                  />
                </div>
                
                {newCredential.schemaId && schemas.find(s => s.id === newCredential.schemaId) && (
                  <div className="mb-3">
                    <label className="form-label">凭证属性</label>
                    {Object.keys(schemas.find(s => s.id === newCredential.schemaId).attributes).map(attr => (
                      <div className="mb-2" key={attr}>
                        <label className="form-label small">{attr}</label>
                        <input 
                          type="text"
                          className="form-control"
                          value={newCredential.attributes[attr] || ''}
                          onChange={(e) => updateCredentialAttribute(attr, e.target.value)}
                          required
                        />
                      </div>
                    ))}
                  </div>
                )}
                
                <button 
                  type="submit" 
                  className="btn btn-primary"
                  disabled={loading || !issuerDid}>
                  {loading ? '处理中...' : '发行凭证'}
                </button>
                {!issuerDid && (
                  <div className="text-danger mt-2">
                    <small>请先创建发行方身份</small>
                  </div>
                )}
              </form>
            </div>
          </div>

          <div className="card">
            <div className="card-body">
              <h3 className="card-title mb-3">已发行凭证</h3>
              {credentials.length === 0 ? (
                <p className="text-muted">暂无已发行凭证</p>
              ) : (
                <div className="table-responsive">
                  <table className="table table-hover">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Schema</th>
                        <th>接收方</th>
                        <th>发行日期</th>
                        <th>状态</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {credentials.map(cred => (
                        <tr key={cred.id}>
                          <td><small>{cred.id}</small></td>
                          <td>{cred.schemaId}</td>
                          <td><small>{cred.subjectDid}</small></td>
                          <td>{new Date(cred.issuanceDate).toLocaleString()}</td>
                          <td>
                            {cred.revoked ? 
                              <span className="badge bg-danger">已撤销</span> :
                              <span className="badge bg-success">有效</span>
                            }
                          </td>
                          <td>
                            {!cred.revoked && (
                              <button 
                                className="btn btn-sm btn-outline-danger"
                                onClick={() => revokeCredential(cred.id)}
                                disabled={loading}>
                                撤销
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default IssuerPage; 